package com.action.gulimall.order.web;

import com.action.gulimall.order.config.AlipayTemplate;
import com.action.gulimall.order.service.OrderService;
import com.action.gulimall.order.vo.OrderConfirmVo;
import com.action.gulimall.order.vo.OrderSubmitVo;
import com.action.gulimall.order.vo.SubmitOrderResponseVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

/**
 * @author sl shilun217@qq.com
 * @Deacription 网页订单相关请求处理
 * @date 2021/07/03/13:55
 **/
@Slf4j
@Controller
public class OrderWebController {

    @Autowired
    OrderService orderService;


    //去订单结算页
    @GetMapping(value="/toTrade")
    public String toTrade(Model model){
        OrderConfirmVo orderConfirmVo = orderService.toTrade();
        model.addAttribute("confirmOrderData", orderConfirmVo);
        return "confirm";
    }

    @PostMapping(value="/submitOrder")
    public String submitOrder(OrderSubmitVo vo, Model model, RedirectAttributes redirectAttributes){
        try{
            SubmitOrderResponseVo submitOrderResponseVo = orderService.submitOrder(vo);
            if(submitOrderResponseVo.getCode()==0){
                //成功跳转到支付页面
                model.addAttribute("submitOrderResp",submitOrderResponseVo);
                return "pay";
            }else{
                //失败返回错误信息重新重定向到订单确认页面
                String msg = "下单失败";
                switch (submitOrderResponseVo.getCode()){
                    case 1: msg += "令牌订单信息过期，请刷新再次提交"; break;
                    case 2: msg += "订单商品价格发生变化，请确认后再次提交"; break;
                    case 3: msg += "库存锁定失败，商品库存不足"; break;
                }
                redirectAttributes.addFlashAttribute("msg",msg);
                return "redirect:http://order.gulimall.com/toTrade";
            }
        }catch(Exception x){
            log.error("下单失败,", x);
            redirectAttributes.addFlashAttribute("msg","下单失败,情稍后重试");
            return "redirect:http://order.gulimall.com/toTrade";
        }
    }


}
